Step 37: Middleware

Let’s revisit the global error handler:

// Global error handler!
app.use((err, req, res, next) => {
  if (err) {
    const code = err.status || 500;
    res.status(code).json({
      status: code,
      message: err.message || `Internal Server Error!`,
    });
  }
  next();
});

What we have created here is a “middleware.”

According to Express documentation:

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

There is plenty of middleware made for Express applications. We will add two popular ones to our app!

Aside: I recommend skimming over Using middleware and Writing middleware for use in Express apps on the Express documentation site.